import { ref } from 'vue'

export interface GameRecord {
  timestamp: number
  moves: string[]
  result?: string
  whiteTime?: number
  blackTime?: number
}

export interface GameState {
  gameTime: {
    white: number
    black: number
  }
  moveHistory: string[]
  capturedPieces: {
    white: string[]
    black: string[]
  }
}

export interface MoveStack {
  value: {
    board: (string | null)[][]
    piece: string
    fromRow: number
    fromCol: number
    toRow: number
    toCol: number
    capturedPiece: string | null
    castlingRights: CastlingState
  }[]
}

interface CastlingRights {
  kingside: boolean
  queenside: boolean
}

interface CastlingState {
  white: CastlingRights
  black: CastlingRights
}

export function useGameState() {
  const gameTime = ref({
    white: 600,
    black: 600
  })
  
  const timer = ref<number | null>(null)
  const moveHistory = ref<string[]>([])
  const capturedPieces = ref({
    white: [] as string[],
    black: [] as string[]
  })
  const gameResult = ref<string | null>(null)
  const moveStack = ref<MoveStack['value']>([])

  const endGame = (result: string) => {
    gameResult.value = result
    pauseTimer()
    saveGame()
  }

  const startTimer = () => {
    if (timer.value) return
    
    timer.value = window.setInterval(() => {
      const currentPlayer = moveHistory.value.length % 2 === 0 ? 'white' : 'black'
      if (gameTime.value[currentPlayer] > 0) {
        gameTime.value[currentPlayer]--
      } else {
        endGame(`${currentPlayer === 'white' ? 'Black' : 'White'} wins by timeout`)
      }
    }, 1000)
  }

  const pauseTimer = () => {
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
  }

  const addMove = (from: string, to: string, piece: string, capture?: string) => {
    const moveNotation = capture ? `${piece}x${to}` : `${piece}${to}`
    moveHistory.value.push(moveNotation)
  }

  const addCapture = (piece: string) => {
    const color = piece.includes('white') ? 'black' : 'white'
    capturedPieces.value[color].push(piece)
  }

  const saveGame = () => {
    const gameRecord: GameRecord = {
      timestamp: Date.now(),
      moves: moveHistory.value,
      whiteTime: gameTime.value.white,
      blackTime: gameTime.value.black
    }
    
    const savedGames = JSON.parse(localStorage.getItem('chessGames') || '[]')
    savedGames.push(gameRecord)
    localStorage.setItem('chessGames', JSON.stringify(savedGames))
  }

  const loadGame = (timestamp: number) => {
    const savedGames = JSON.parse(localStorage.getItem('chessGames') || '[]')
    const game = savedGames.find((g: GameRecord) => g.timestamp === timestamp)
    if (game) {
      moveHistory.value = game.moves
      gameTime.value = {
        white: game.whiteTime || 600,
        black: game.blackTime || 600
      }
      return true
    }
    return false
  }

  const undoMove = () => {
    const lastMove = moveStack.value.pop()
    if (!lastMove) return false

    // 实现悔棋逻辑
    moveHistory.value.pop()
    return true
  }

  return {
    gameTime,
    moveHistory,
    capturedPieces,
    gameResult,
    moveStack,
    startTimer,
    pauseTimer,
    addMove,
    addCapture,
    saveGame,
    loadGame,
    endGame,
    undoMove
  }
} 